package bTree.LeetCode;

import java.util.Random;

public class 数组中的第K个最大元素 {
    public int findKthLargest(int[] nums, int k) {
        int left = 0, right = nums.length - 1;
        int target = nums.length - k;
        partition(nums, left, right);
        return nums[target];
    }


    private void partition(int[] nums, int left, int right) {
        if (left >= right) {
            return;
        }
        int slow = left, medium = left, fast = right;
        int point = nums[right];
        while (medium <= fast) {
            if (nums[medium] > point) {
                swap(nums,medium,fast);
                fast--;
            } else if (nums[medium]<point) {
                swap(nums,slow,medium);
                medium++;
                slow++;
            }else {
                medium++;
            }
        }
        partition(nums,left,slow-1);
        partition(nums,fast+1,right);
    }

    private void swap(int[] nums, int indexA, int indexB) {
        int temp = nums[indexA];
        nums[indexA] = nums[indexB];
        nums[indexB] = temp;
    }
}